#!/usr/bin/env bash

set -e
set -x

# Run using jt build parser

###### Change these to tastes ######
JAY=jay
RUBY=ruby
PARSER_BASE=RubyParser
YYTABLE_PREFIX=
#DEBUG=true
###### Do not change below ######

unset GEM_HOME GEM_PATH GEM_ROOT

if [ "$1" != "" ]; then
  PARSER_BASE=$1
  shift
fi

if [ "$1" != "" ]; then
  YYTABLE_PREFIX=$1
fi

if [ "$DEBUG" != "" ]; then
  DEBUG_FLAG=-t
  # Nonesense...my script-fu is weak
  DEBUG_STRIP="xdyhbk"
else
  DEBUG_FLAG=
  DEBUG_STRIP="^//t"
fi

echo "Generating Parser '$PARSER_BASE' w/ YYTable prefix of '$YYTABLE_PREFIX'"

repo_root=$(pwd)

PARSER_DIR=src/main/java/org/truffleruby/parser/parser

pushd $PARSER_DIR

# Generate grammar as intermediate file
$JAY $DEBUG_FLAG $PARSER_BASE.y < skeleton.parser | grep -v $DEBUG_STRIP >$PARSER_BASE.out

# Patch file to get around Java static initialization issues plus extract
# a bunch of stuff to separate file (yytables).
$RUBY $repo_root/tool/patch_parser.rb $PARSER_BASE.out $YYTABLE_PREFIX > $PARSER_BASE.out2
$RUBY $repo_root/tool/optimize_parser.rb $PARSER_BASE.out2 $YYTABLE_PREFIX > $PARSER_BASE.java
rm -f $PARSER_BASE.out $PARSER_BASE.out2

popd
